package demo2;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-05-05
 * Time: 15:45
 */
public class test {
    public boolean containsDuplicate(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        for (Map.Entry<Integer, Integer> e : entries) {
            int val = e.getValue();
            if (val >= 2) {
                return true;
            }
        }
        return false;
    }

    /**
     * 给你一个整数数组 nums 和一个整数 k
     * 判断数组中是否存在两个 不同的索引 i 和 j
     * 满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在，返回 true
     * 否则，返回 false 。
     *
     * @param nums
     * @param k
     * @return
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {

        //[1,0,1,1],k = 1
        boolean flg = false;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], i);
            } else {
                int Index = map.get(nums[i]);
                if (Math.abs(i - Index) <= k) {
                    flg = true;
                }
                map.put(nums[i], i);
            }
        }
        return flg;
/*        boolean flg = false;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    if (Math.abs(i - j) <= k) {
                        flg = true;
                    }
                }
            }
        }
        return flg;*/
    }
}
